package pricelist;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import dbmanager.DBManager;

public class GenerateCSV
{
	String path;
	DBManager db;
	String tablename;
	public GenerateCSV() 
	{
		
	}
	void setPath(String path)
	{
		this.path = path;
	}
	public void setDb(DBManager db) {
		this.db = db;
	}
	public void setTablename(String tablename) {
		this.tablename = tablename;
	}
	public void generate()
	{
		StringBuffer strBuff = new StringBuffer(); 
		ResultSet rs = db.getSelect("select * from "+tablename);
		try 
		{
			ResultSetMetaData col = rs.getMetaData();
			int count = col.getColumnCount();
			for(int i=1;i<=count;i++)
			{
				strBuff.append(col.getColumnName(i)+"\t");
			}
			strBuff.append("\n");
			while(rs.next())
			{
				for(int i=1;i<=count;i++)
				{
					try 
					{
						strBuff.append(rs.getString(i)+"\t");
					} catch (Exception e) {
						strBuff.append("null\t");
					}
				}
				strBuff.append("\n");
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		//Writing to File
		path = path + "//" + tablename + ".csv";
		
		try 
		{
			RandomAccessFile raf = new RandomAccessFile(path,"rws");
			raf.writeBytes(strBuff.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) 
	{
		DBManager db = new DBManager();
		db.getConnect();
		String path ="//home//server//Report//CSV//";
		String tablename = "itemreqreport";
		GenerateCSV csv = new GenerateCSV();
		csv.setDb(db);
		csv.setPath(path);
		csv.setTablename(tablename);
		csv.generate();
	}
}
